package handlers

import (
	"strings"
	"ticket/internal/db"
	"ticket/internal/db/model"
	"ticket/internal/schemas"
	"ticket/pkg/utils"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

type TaskHandler struct{}

func RegisterTaskRouter(group *gin.RouterGroup) {
	service := &TaskHandler{}
	group.POST("/create", service.Create)
	group.GET("/:id", service.Get)
	group.GET("/list", service.List)
}

// Create godoc
// @Summary 创建任务
// @Description 创建任务
// @Tags 任务
// @ID /task/create
// @Accept json
// @Produce json
// @Param task body schemas.CreateTask true "任务信息"
// @Success 200 {object} schemas.Response{data=model.Task} "任务创建成功"
// @Router /task/create [post]
func (h *TaskHandler) Create(c *gin.Context) {
	params := &schemas.CreateTask{}
	if err := params.BindValidParam(c); err != nil {
		schemas.ResponseError(c, schemas.TaskParamInvalid, err)
		return
	}
	user, ok := utils.GetCurrentUser(c)
	if !ok {
		schemas.ResponseError(c, schemas.TaskParamInvalid, errors.New("用户不存在"))
		return
	}

	handlers := make([]model.User, 0)
	for _, handler := range params.Handlers {
		handlers = append(handlers, model.User{ID: handler})
	}
	task := &model.Task{
		ID:        params.ID,
		Name:      params.Name,
		ParentID:  params.ParentID,
		Describe:  params.Describe,
		ProjectID: params.ProjectID,
		Type:      params.Type,
		KeyWords:  params.KeyWords,
		CreateBy:  user.UserName,
		UpdateBy:  user.UserName,
		State:     params.State,
		AnnexUrls: strings.Join(params.AnnexUrls, ","),
		Handlers:  handlers,
	}
	if err := task.Create(db.GormDB); err != nil {
		schemas.ResponseError(c, schemas.TaskCreateFailed, err)
		return
	}
	schemas.ResponseSuccess(c, task)
}

// Get godoc
// @Summary 获取任务
// @Description 获取任务
// @Tags 任务
// @ID /task/:id
// @Accept json
// @Produce json
// @Param id path uint true "任务id"
// @Success 200 {object} schemas.Response{data=model.Task} "任务获取成功"
// @Router /task/:id [get]
func (h *TaskHandler) Get(c *gin.Context) {
	id := c.Param("id")
	task := &model.Task{}
	task, err := task.GetByID(db.GormDB, id)
	if err != nil {
		schemas.ResponseError(c, schemas.TaskParamInvalid, err)
		return
	}
	schemas.ResponseSuccess(c, task)
}

// List godoc
// @Summary 获取任务列表
// @Description 获取任务列表
// @Tags 任务
// @ID /task/list
// @Accept json
// @Produce json
// @Success 200 {object} schemas.Response{data=[]model.Task} "任务列表获取成功"
// @Router /task/list [get]
func (h *TaskHandler) List(c *gin.Context) {
	params := &schemas.QueryTask{}
	if err := params.BindValidParam(c); err != nil {
		schemas.ResponseError(c, schemas.TaskParamInvalid, err)
		return
	}
	task := &model.Task{}
	tasks, err := task.List(db.GormDB, params)
	if err != nil {
		schemas.ResponseError(c, schemas.TaskParamInvalid, err)
		return
	}
	schemas.ResponseSuccess(c, tasks)
}
